package com.example.task02_dao;

import com.example.task02_bean.User;
import com.example.task02_util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImp implements  UserDao{

    @Override
    public User userlogin(User user) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            //1.获取数据库连接
            connection = DBUtil.getConnection();
            //2.准备SQL语句
            String sql="select * from t_user where username=? and password=?";
            //3.执行SQL语句并获取结果并返回
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, user.getUsername());
            preparedStatement.setString(2, user.getPassword());
            resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                User tu=new User(resultSet.getString("username"),resultSet.getString("password"));
                return tu; //表示查找成功
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                //4.释放相关的资源
                DBUtil.closeResource(connection,preparedStatement);
                if(null!=resultSet) {
                    resultSet.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null; //表示查找失败
    }
}
